import axios from 'axios';
import qs from 'qs';
import { Toast } from "vant";
import request from './request.js'
import store from "../store/index.js"
import router from '@/router'
import Axios from './pending'
//响应时间
axios.defaults.timeout = 15000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;'
let baseUrl = "https://www.jikeshiyong.cn/api/";
// let baseUrl = "https://test.jikeshiyong.cn/api/";


//请求拦截器
axios.interceptors.request.use(config => {
    Axios.remvoePending(config)
    Axios.addPending(config) // 将当前请求添加到pending中
    //在发送请求之前做某件事
    if (config.method === 'post' && config.data.constructor !== FormData) {
        config.data = qs.stringify(config.data);
    }
    return config
}, error => {
    return Promise.reject(error)
}, (error) => {
    Toast('错误的传参');
    return Promise.reject(error);
})


// 添加响应拦截器
// axios.interceptors.response.use(response => {
//     Axios.remvoePending(response.config)
//     return response;
// }, error => {
//     console.log(error, 'error')
//     // 对响应错误做点什么
//     error.config && Axios.remvoePending(error.config)
//     // return Promise.resolve({ status: 1, data: { msg: '网络繁忙，请重新提交' } })
//     return Promise.reject(error)
// });

// 处理loading
const toast = () =>
    Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        loadingType: "spinner",
        className: "loading-icon",
        message: "加载中..."
    });
// //返回状态判断(添加响应拦截器)
// axios.interceptors.response.use((res) =>{
//   Toast.clear();
//   //对响应数据做些事
//   if(!res.data.success){
//     return Promise.resolve(res);
//   }
//   return res;
// }, (error) => {
//   if (error && error.stack.indexOf('timeout') > -1) {
//     Toast('请求超时')
//   }
//   return Promise.reject(error);
// });
var msg = ''
axios.interceptors.response.use(function(response) {
    Toast.clear();
    // 对响应数据做点什么
    return response;
}, function(err) {
    console.log(err, 4)
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                msg = '请求错误(400)';
                break;
            case 401:
                msg = '未授权，请重新登录(401)';
                break;
            case 403:
                msg = '拒绝访问(403)';
                break;
            case 404:
                msg = '请求出错(404)';
                break;
            case 408:
                msg = '请求超时(408)';
                break;
            case 500:
                msg = '服务器错误(500)';
                break;
            case 501:
                msg = '服务未实现(501)';
                break;
            case 502:
                msg = '网络错误(502)';
                break;
            case 503:
                msg = '服务不可用(503)';
                break;
            case 504:
                msg = '网络超时(504)';
                break;
            case 505:
                msg = 'HTTP版本不受支持(505)';
                break;
            default:
                msg = `连接出错(${err.response.status})!`;
        }
        Toast({
            message: msg,
            position: 'bottom'
        });
    } else {
        msg = '连接服务器失败!'
    }

    var originalRequest = err.config;
    if (err.code == 'ECONNABORTED' && err.message.indexOf('timeout') != -1 && !originalRequest._retry) {
        originalRequest._retry = true
        return axios.request(originalRequest);
    }
    return Promise.reject(err);
});

// 文件上传
export function fetchFile(url, file) {
    toast();
    var _param = {}
        // 输出所有的 key
    for (var key of file.keys()) {
        if (!(file.get(key) instanceof File)) {
            _param[key] = file.get(key)
        }
    }
    if (typeof _param == "object") {
        let token = request.genToken();
        axios.defaults.headers.post['Token'] = token;
    }
    axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
    return new Promise((resolve, reject) => {
        file.append('m', '2020jksy')
        axios.post(baseUrl + url, file)
            .then(response => {
                Toast.clear();
                if (response && response.data.errorCode) fnExitLogin();
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

export function fnExitLogin() {
    store.commit('REMOVE_COUNT', { token: {}, uid: '', aeskey: '' });
    store.commit('REMOVE_RZ', false);
    var query = {};
    var _from = router.currentRoute.name ? router.currentRoute.name : 'home';
    // 输出所有的 key
    for (var key in router.currentRoute.query) {
        query[key] = router.currentRoute.query[key]
    }
    query['from'] = _from;
    router.push({
        name: 'login', //这个name就是你刚刚配置在router里边的name
        params: router.currentRoute.params,
        query: query
    })
}

//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;';
    if (!params.isLoading) toast();
    if (params.isToken) {
        if (typeof params == "object") {
            if (params.isToken) delete params.isToken
            let token = request.genToken();
            axios.defaults.headers.post['Token'] = token;
        }
    }
    return new Promise((resolve, reject) => {
        let {isToken, isLoading, ...param} = params;
        param.m = '2020jksy'
        axios.post(baseUrl + url, param)
            .then(response => {
                if (response && response.data.errorCode) fnExitLogin();
                resolve(response.data);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}


//返回一个Promise(发送get请求)
export function fetchGet(url, params) {
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;';
    if (!params.isLoading) toast();
    var _param = { params: params };
    if (params.isToken) {
        if (typeof params == "object") {
            if (params.isToken) delete params.isToken
            let token = request.genToken();
            let {isToken, isLoading, ...param} = params;
            param.m = '2020jksy'
            _param = {
                params: param,
                headers: {
                    Token: token
                }
            }
        }
    } else {
        let {isToken, isLoading, ...param} = params;
        param.m = '2020jksy'
        _param = {
            params: param
        }
    }
    return new Promise((resolve, reject) => {
        axios.get(baseUrl + url, _param)
            .then(response => {
                if (response && response.data.errorCode) fnExitLogin();
                resolve(response.data)
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}
export default {
    fetchPost,
    fetchGet,
    fetchFile,
    fnExitLogin
}